package memento;

import java.io.*;

/**
 * CMemento 序列化
 * 然后找个对象拿着或者落到磁盘。
 * Serializable 对象的持久化。
 * Serializable 必须写不写序列化运行报错。
 * objectOutputStream.writeObject objectOutputStream.writeObject 连续写两个对象 读取先写谁就先读谁。
 */
class CMemento implements Serializable{
   int x = 10;
   transient int y = 20; // transient序列化的时候不往外写，但是没写出调用也不报错。
   public void save() throws IOException {
       File file = new File("./src/main/java/memento/test.txt");
       FileOutputStream fileOutputStream = new FileOutputStream(file);
       ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
       objectOutputStream.writeObject(this);
       objectOutputStream.close();
       fileOutputStream.close();
   }
   public void read() throws IOException, ClassNotFoundException {
       File file = new File("./src/main/java/memento/test.txt");
       FileInputStream fileInputStream = new FileInputStream(file);
       ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
       CMemento cMemento = (CMemento) objectInputStream.readObject();
       System.out.println(cMemento.x);
       System.out.println(cMemento.y);
   }
}

public class Memento {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        System.out.println("memento");

        CMemento cMemento = new CMemento();
        cMemento.save();
        cMemento.read();
    }
}
